package com.example.tianling.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tianling.common.annotation.Login;
import com.example.tianling.common.annotation.LoginUser;
import com.example.tianling.common.params.DownLoadDo;
import com.example.tianling.common.params.PublishLearnArticleDo;
import com.example.tianling.common.params.PublishTrainArticleDo;
import com.example.tianling.common.params.SearchDo;
import com.example.tianling.common.utils.MinioUtils;
import com.example.tianling.common.utils.R;
import com.example.tianling.common.utils.Check;
import com.example.tianling.common.utils.RedisUtils;
import com.example.tianling.common.vo.TrainArticleVo;
import com.example.tianling.common.vo.article;
import com.example.tianling.common.vo.articleCommonVo;
import com.example.tianling.common.vo.forumVo;
import com.example.tianling.entity.ArticleEntity;
import com.example.tianling.entity.UserEntity;
import com.example.tianling.service.ForumService;
import com.example.tianling.service.WxService;
import org.json.JSONException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;

import static com.example.tianling.common.utils.ImageUtils.compress;
import static com.example.tianling.common.utils.toImg.convertBase64ToMultipartFile;

@Controller
public class ForumController {

    @Autowired
    private ForumService forumService;
    @Autowired
    private RabbitTemplate rabbitTemplate ;//使用RabbiTeme,提供了接受发送方法

    @Autowired
    private WxService wxService;

    @Autowired
    private RedisUtils redisUtils;

    //根据id 返回对应的数据
    @Login
    @PostMapping("/forum")
    @ResponseBody
    public R loadForum(@LoginUser UserEntity user) {
        //这个是加载社区页面的，所以只需要返回第一页的数据就好
        IPage<article> learnArticle= forumService.load(1,1);
        for (article article0 : learnArticle.getRecords()) {
            Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
            Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
            Integer like_now = like ? 1 : 0;
            Integer save_now = save ? 1 : 0;
            article0.setLike(Long.valueOf(like_now));
            article0.setSave(Long.valueOf(save_now));
        }
        IPage<article> chatArticle= forumService.load(1,2);
        for (article article0 : chatArticle.getRecords()) {
            Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
            Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
            Integer like_now = like ? 1 : 0;
            Integer save_now = save ? 1 : 0;
            article0.setLike(Long.valueOf(like_now));
            article0.setSave(Long.valueOf(save_now));
        }
        IPage<TrainArticleVo> trainArticle= forumService.loadTrian(1,3);
        for (TrainArticleVo article0 : trainArticle.getRecords()) {
            Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
            Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
            Integer like_now = like ? 1 : 0;
            Integer save_now = save ? 1 : 0;
            article0.setLike(Long.valueOf(like_now));
            article0.setSave(Long.valueOf(save_now));
        }
        return R.success(new forumVo(learnArticle,chatArticle,trainArticle));
    }

    @PostMapping("/forum/down_load.do")
    @ResponseBody
    public R down_load(@RequestBody DownLoadDo downLoadDo) {
        //下滑加载，通关接受前端传来的帖子类型和具体页数，返回对应的页数数据
        int pageNum = Integer.parseInt(downLoadDo.getPage());
        int typeNum = Integer.parseInt(downLoadDo.getTypeNum());
        if (typeNum==1) {
            IPage<article> newArticle= forumService.load(pageNum,typeNum);
//            for (article article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(newArticle,null,null));
        }
        else if(typeNum==2){
            IPage<article> newArticle= forumService.load(pageNum,typeNum);
//            for (article article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(null,newArticle,null));
        }
        else if(typeNum==3){
            IPage<TrainArticleVo> newArticle= forumService.loadTrian(pageNum,typeNum);
//            for (TrainArticleVo article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(null,null,newArticle));
        }
        return null;
    }

    //上滑刷新，获取该帖子类型的十条数据
    @PostMapping(value="/forum/up_refresh.do")
    @ResponseBody
    public R up_refresh(@RequestBody String params) {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        String typeNumStr = paramsJSONObject.getString("typeNum");
        int typeNum = Integer.parseInt(typeNumStr);
        if (typeNum==1) {
            IPage<article> newArticle= forumService.load(1,typeNum);
//            for (article article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(newArticle,null,null));
        }
        else if(typeNum==2){
            IPage<article> newArticle= forumService.load(1,typeNum);
//            for (article article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(null,newArticle,null));
        }
        else if(typeNum==3){
            IPage<TrainArticleVo> newArticle= forumService.loadTrian(1,typeNum);
//            for (TrainArticleVo article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(null,null,newArticle));
        }
        return null;
    }

    @PostMapping(value="/search/down_load.do")
    @ResponseBody
    public R search_load(@RequestBody SearchDo searchDo) {
        Integer pageNum = Integer.parseInt(searchDo.getPage());
        Integer typeNum = Integer.parseInt(searchDo.getTypeNum());
        String keyword = searchDo.getKeyword();

        if (typeNum==1) {
            IPage<article> newArticle= forumService.search(pageNum,typeNum,keyword);
//            for (article article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(newArticle,null,null));
        }
        else if(typeNum==2){
            IPage<article> newArticle= forumService.search(pageNum,typeNum,keyword);
//            for (article article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(null,newArticle,null));
        }
        else if(typeNum==3){
            IPage<TrainArticleVo> newArticle= forumService.searchTrain(pageNum,typeNum,keyword);
//            for (TrainArticleVo article0 : newArticle.getRecords()) {
//                Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//                Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//                Integer like_now = like ? 1 : 0;
//                Integer save_now = save ? 1 : 0;
//                article0.setLike(Long.valueOf(like_now));
//                article0.setSave(Long.valueOf(save_now));
//            }
            return R.success(new forumVo(null,null,newArticle));
        }
        return null;
    }

    //搜索帖子，关键词在标题中存在就寻找出来
    @PostMapping(value="/search/search.do")
    @ResponseBody
    public R search_and_refresh(@RequestBody String params) {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        String keyword = paramsJSONObject.getString("keyword");
        IPage<article> learnArticle= forumService.search(1,1,keyword);
//        for (article article0 : learnArticle.getRecords()) {
//            Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//            Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//            Integer like_now = like ? 1 : 0;
//            Integer save_now = save ? 1 : 0;
//            article0.setLike(Long.valueOf(like_now));
//            article0.setSave(Long.valueOf(save_now));
//        }
        IPage<article> chatArticle= forumService.search(1,2,keyword);
//        for (article article0 : chatArticle.getRecords()) {
//
//            Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//            Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//
//            Integer like_now = like ? 1 : 0;
//            Integer save_now = save ? 1 : 0;
//            article0.setLike(Long.valueOf(like_now));
//            article0.setSave(Long.valueOf(save_now));
//        }
        IPage<TrainArticleVo> trainArticle= forumService.searchTrain(1,3,keyword);
//        for (TrainArticleVo article0 : trainArticle.getRecords()) {
//            Boolean like = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString(),"like");
//            Boolean save = forumService.is_follow_like_save(user.getUserId().toString(),article0.getArticleId().toString().toString(),"save");
//            Integer like_now = like ? 1 : 0;
//            Integer save_now = save ? 1 : 0;
//            article0.setLike(Long.valueOf(like_now));
//            article0.setSave(Long.valueOf(save_now));
//        }
        return R.success(new forumVo(learnArticle,chatArticle,trainArticle));
    }

    //发贴，参数保存参数对象，插入数据库
    @Login
    @RequestMapping(value="/article/publish_learnArticle.do",method = RequestMethod.POST)
    @ResponseBody
    public R publish_learnArticle(@RequestBody PublishLearnArticleDo publishLearnArticleDo,@LoginUser UserEntity user) throws JSONException, IOException {
        Map<String, Object> map = new HashMap<>();
        String context = publishLearnArticleDo.getTitle()+publishLearnArticleDo.getContext();
        List<String> img = publishLearnArticleDo.getArticleImg();
        Check check = new Check();
        int textCheack = check.text(context);
        int imgCheack = 1;
//        for(int i =0;i<img.size();i++){
//            String decodedUrl = URLDecoder.decode(img.get(i), StandardCharsets.UTF_8.name());
//            String base64Data = decodedUrl.substring(decodedUrl.indexOf(',') + 1);
//            String  encodedData  = URLEncoder.encode(base64Data, "UTF-8");
//            imgCheack = check.image(encodedData.replaceAll("\\+","%2B"));
//            imgCheack = 2>imgCheack?imgCheack:2;
//        }
        if (textCheack==2||imgCheack==2){
            return new R(408,"内容涉嫌违规");
        }
        String userId = user.getUserId().toString();
        try {
            Map<String,Object> new_map = new HashMap<>();
            new_map.put("userId",userId);
            new_map.put("context",publishLearnArticleDo.getContext());
            new_map.put("title",publishLearnArticleDo.getTitle());
            new_map.put("arctleType",publishLearnArticleDo.getArctleType());
            new_map.put("time",publishLearnArticleDo.getTime());
            new_map.put("images",publishLearnArticleDo.getArticleImg());
            rabbitTemplate.convertAndSend("topicExchangeSubbmit","topic.subbmit_chat_lrean",new_map);
        }catch (Exception e){
            e.printStackTrace();
        }

        map.put("arctle_state", 200);
        return R.success(map);
    }


    @Login
    @RequestMapping(value="/article/wx_publish_learnArticle.do",method = RequestMethod.POST)
    @ResponseBody
    public R wx_publish_learnArticle(@RequestBody PublishLearnArticleDo publishLearnArticleDo,@LoginUser UserEntity user) throws JSONException, IOException {
        Map<String, Object> map = new HashMap<>();
        String context = publishLearnArticleDo.getTitle()+publishLearnArticleDo.getContext();
        List<String> img = publishLearnArticleDo.getArticleImg();

        // 检测文本
        boolean isContext = wxService.textCheck(user.getOpenId(), context, 3);
        if (isContext) {

            ArticleEntity articleEntity = forumService.publish_learn(publishLearnArticleDo,user);
            String articleImgs = articleEntity.getArticleImg();
            articleImgs.replace("[", "");
            articleImgs.replace("]", "");

            // 检测图片
            List<String> articleImgList = Arrays.asList(articleImgs.split(","));
            for (String articleImgUrl : articleImgList) {
                String traceId = wxService.mediaCheck(user.getOpenId(), articleImgUrl, 2, 3);

                Map<String, Object> traceMap = new HashMap<>();
                traceMap.put("articleId", articleEntity.getArticleId());
                traceMap.put("type", "articleImg");
                redisUtils.set("trace_"+traceId, traceMap);
            }
        }

        return R.success();
    }

    //发贴，参数保存参数对象，插入数据库
    @Login
    @RequestMapping(value="/article/publish_trainArticle.do",method = RequestMethod.POST)
    @ResponseBody
    public R publish_trainArticle(@RequestBody PublishTrainArticleDo publishTrainArticleDo,@LoginUser UserEntity user) throws JSONException, IOException, ParseException {
        String userId = user.getUserId().toString();
        String context = publishTrainArticleDo.getContext();
        Check check = new Check();
        int textCheack = check.text(context);
        if (textCheack==2){
            return new R(408,"内容涉嫌违规");
        }
        Integer roomId = forumService.publish_train(publishTrainArticleDo,Integer.toString(user.getUserId()));
        if(roomId==-1){
            return R.error(409,"预约失败已预约房间");
        }
        try {
            Map<String,Object> new_map = new HashMap<>();
            new_map.put("userId",userId);
            new_map.put("context",publishTrainArticleDo.getContext());
            new_map.put("title",publishTrainArticleDo.getRoomName());
            new_map.put("arctleType",publishTrainArticleDo.getArctleType());
            new_map.put("roomId",roomId);
            rabbitTemplate.convertAndSend("topicExchangeSubbmit","topic.subbmit_chat_lrean",new_map);
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("reserveRoomId",roomId);
        return R.success(map);
    }



    //发贴，参数保存参数对象，插入数据库
    @Login
    @RequestMapping(value="/article/wx_publish_trainArticle.do",method = RequestMethod.POST)
    @ResponseBody
    public R wx_publish_trainArticle(@RequestBody PublishTrainArticleDo publishTrainArticleDo,@LoginUser UserEntity user) throws JSONException, IOException, ParseException {
        String userId = user.getUserId().toString();
        String context = publishTrainArticleDo.getContext();
        Map<String, Object> map = new HashMap<>();
        // 检测文本
        boolean isContext = wxService.textCheck(user.getOpenId(), context, 3);
        if (isContext) {
            Integer roomId = forumService.publish_train(publishTrainArticleDo,Integer.toString(user.getUserId()));
            if(roomId==-1){
                return R.error(409,"预约失败已预约房间");
            }
            PublishLearnArticleDo publishLearnArticleDo = new PublishLearnArticleDo();
            publishLearnArticleDo.setContext(publishTrainArticleDo.getContext());
            publishLearnArticleDo.setTitle(publishTrainArticleDo.getRoomName());
            publishLearnArticleDo.setArctleType(publishTrainArticleDo.getArctleType());
            forumService.publish_learn(publishLearnArticleDo,user);
            map.put("reserveRoomId",roomId);
        }

        return R.success(map);
    }
}
